<template>
	<view class="index">
		<!-- 顶部导航 -->
		<view class="index_navbar"
			:style="{paddingTop:safeAreaInsets?.top+'px',height:selectTab === 0 && scrollTopView < 88?'170px':'94rpx'}">
			<view class="index_navbar_top">
				<view class="index_navbar_top_location" @click="handleOpenLocation">
					<image src="http://qianxueapplet.suoeryun.com/location.png"></image>
					<text>{{vuex_location?.areaName}}</text>
				</view>
				<view class="index_navbar_top_tabs">
					<text :class="{selected:selectTab === item?.id}" @click="handleTabs(item)" v-for="item in tabList"
						:key="item?.id">{{item?.name}}</text>
				</view>
			</view>
		</view>
		<template v-if="selectTab === 0">
			<scroll-view :scroll-top="activityScrollTop" scroll-y="true" refresher-enabled="true"
				:refresher-triggered="activityTriggered" @refresherrefresh="activityOnRefresh" :refresher-threshold="50"
				@scrolltolower="activityScrolltolower" class="index_scroll_activity_view"
				@scroll="handleActivityScroll">
				<!-- 轮播图 -->
				<view class="index_swiper">
					<u-swiper :list="swiperList" indicator indicatorMode="dot" circular height="182" radius="5"
						keyName="imageUrl" @click="handleSwiperclick"></u-swiper>
				</view>
				<view class="index_body">
					<!-- 类型 -->
					<view class="index_function">
						<view class="index_function_item" @click="handleJump('亲子专属')">
							<image src="http://qianxueapplet.suoeryun.com/offspring.png">
							</image>
							<text>亲子专属</text>
						</view>
						<view class="index_function_item" @click="handleJump('小学专属')">
							<image src="http://qianxueapplet.suoeryun.com/primarySchool.png">
							</image>
							<text>小学专属</text>
						</view>
						<view class="index_function_item" @click="handleJump('初中专属')">
							<image src="http://qianxueapplet.suoeryun.com/juniorHigh.png">
							</image>
							<text>初中专属</text>
						</view>
						<view class="index_function_item" @click="handleJump('高中专属')">
							<image src="http://qianxueapplet.suoeryun.com/highSchool.png">
							</image>
							<text>高中专属</text>
						</view>
					</view>
					<!-- 研习互动 -->
					<view class="index_study" @click="handleJump('研习活动')">
						<text class="index_study_left">研习活动</text>
						<view class="index_study_right">更多<u-icon name="arrow-right" color="#FA9353" size="11"></u-icon>
						</view>
					</view>
					<!-- tabs -->
					<u-tabs :list="list" @click="handleTabClick" :activeStyle="{
						color:'#FA9353',fontWeight: 'bold', fontSize:'15px'}" :inactiveStyle="{color: '#333333',fontSize:'14px',}"
						lineColor="#FA9353"></u-tabs>
					<!-- 活动内容 -->
					<template v-if="activityList?.length > 0">
						<view class="index_activity">
							<activityCards v-for="item in activityList" :key="item?.id" :item="item"
								@handleEmit="handleEmit">
							</activityCards>
						</view>
						<u-loadmore :status="activityStatus" @loadmore="activityScrolltolower"
							v-if="activityStatus !== 'nomore'"></u-loadmore>
					</template>
					<u-empty v-else marginTop="10" text="暂无活动～"
						icon="http://qianxueapplet.suoeryun.com/hd.png"></u-empty>
				</view>
			</scroll-view>
			<!-- 省市区 -->
			<cityPicker :column="3" :default-value="defaultValue" :mask-close-able="true" @confirm="confirm"
				@cancel="cancel" :visible="cityPickerVisible" />
		</template>
		<template v-else-if="selectTab === 1">
			<!-- 研习基地 -->
			<view v-if="dataSouse?.length > 1 || params?.search" class="index_scroll_base">
				<view class="index_scroll_search">
					<u-search placeholder="研学基地关键词搜索" v-model="keyword" :clearabled="true" :show-action="false"
						height="30" @change="handleSearchChange" @clear="handleSearchChange"></u-search>
				</view>
				<scroll-view :scroll-top="scrollTop" scroll-y="true" refresher-enabled="true"
					:refresher-triggered="triggered" @refresherrefresh="onRefresh" :refresher-threshold="50"
					@scrolltolower="scrolltolower" class="index_scroll_base_view">
					<baseCard :item="item" v-for="item in dataSouse" :key="item?.id" @handleEmit="handleBaseEmit">
					</baseCard>
					<u-loadmore :status="status" @loadmore="scrolltolower" v-if="status !== 'nomore'"></u-loadmore>
				</scroll-view>
			</view>
			<baseDetails v-else :baseinfo="baseinfo"></baseDetails>
		</template>
	</view>
	<!-- 评论 -->
	<comment ref="commentRef" @close="handleCommentClose"></comment>
	<!-- 分享 -->
	<customShare ref="shareRef"></customShare>
	<!-- 客服按钮 -->
	<button open-type="contact" class="index_service_btn">
		<image src="http://qianxueapplet.suoeryun.com/homeService.png"></image>
	</button>
</template>

<script setup lang="ts">
	import { onMounted, getCurrentInstance, ref, reactive, unref } from "vue";
	import { qxHomebaseManageList, qxHomebaseManageQueryById, qxActivityManageList, addressResolution, selectXcxList } from "@/config/index.api";
	import { onReachBottom, onHide } from "@dcloudio/uni-app";
	import activityCards from '@/components/activityCards.vue';
	import baseDetails from '@/components/baseDetails.vue';
	import baseCard from '@/components/baseCard.vue';
	import cityPicker from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker.vue';
	import comment from "@/components/comment.vue";
	import customShare from "@/components/customShare.vue";

	const { proxy } = getCurrentInstance();
	const commentRef = ref();
	const shareRef = ref();
	// 轮播图数据
	const swiperList = ref([
		{ imageUrl: 'http://qianxueapplet.suoeryun.com/swiper.png' },
		{ imageUrl: 'http://qianxueapplet.suoeryun.com/swiper1.png' },
		{ imageUrl: 'http://qianxueapplet.suoeryun.com/swiper2.png' },
	]);
	const cityPickerVisible = ref(false);
	const defaultValue = ref('');

	const tabList = [{ id: 0, name: '最新活动' }, { id: 1, name: '研学基地' }];
	// 导航激活下标
	const selectTab = ref(0);
	// 系统参数
	const { safeAreaInsets } = uni.getSystemInfoSync();
	// tabs数据
	const list = [{
		name: '未开始',
		id: 1,
	}, {
		name: '进行中',
		id: 2,
	}, {
		name: '已结束',
		id: 3,
	}];
	// 最新活动
	const activityList = ref([]);
	const activityPagination = reactive({ pageNo: 1, total: 0, pageSize: 10 });
	const activityStatus = ref('loadmore');
	// 活动参数
	const activityParams = ref({ activityStatus: 1 });
	const activityIndex = ref(0);
	const activityScrollTop = ref(0);
	const activityTriggered = ref(false);
	const scrollTopView = ref(0);

	// 研学基地
	const dataSouse = ref([]);
	const baseinfo = ref({});
	const triggered = ref(false);
	const scrollTop = ref(0);
	const status = ref('loadmore');
	const keyword = ref('');
	const params = ref({ search: '' });
	// 分页计数
	const pagination = reactive({ pageNo: 1, total: 0, pageSize: 10 });

	onHide(() => {
		commentRef.value.handleClose();
	})

	onMounted(() => {
		// 默认地区
		defaultValue.value = proxy['vuex_location']!['code'] ?? '';
		// 轮播图
		handleSlideshow();
		uni.authorize({
			scope: 'scope.userLocation',
			success(res) {
				console.log(res, 'authorize');
				uni.getLocation({
					type: 'gcj02',
					success: async function (res) {
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						const data = await addressResolution({ lat: res.latitude, lng: res.longitude });
						console.log(data, 'data');
						let result = data?.result;
						if (result) {
							uni.$u.vuex('vuex_location', {
								areaName: result?.ad_info?.city,
								cityName: result?.ad_info?.district,
								code: result?.ad_info?.adcode,
								provinceName: result?.ad_info?.province,
								name: result?.address,
							});
							uni.$u.vuex('vuex_current_position', result);
						}
					}
				});
			}, fail(err) {
				console.log(err, 'authorize err');
				uni.$u.vuex('vuex_location', {
					areaName: "阜南县",
					cityName: "阜阳市",
					code: "341225",
					name: "安徽省阜阳市阜南县",
					provinceName: "安徽省",
				});
			}
		})
		// 最新活动
		activityPagination.pageNo == 1
		loadActivityData();
	})
	/**
	 * 跳转
	 */
	function handleJump(title) {
		uni.$u.route('/pages/index/activityList', {
			title
		});
	}

	/**
	 * 轮播
	 */
	async function handleSlideshow() {
		const res = await selectXcxList({});
		console.log(res, 'res');
		if (res?.length > 0)
			swiperList.value = res;
	}
	/**
	 * 滚动监听
	 */
	onReachBottom(() => {
		console.log('3');
		if (unref(selectTab) === 0) {//最新活动
			activityScrolltolower();
		} else {//研习基地
			scrolltolower();
		}
	})

	/**
	 * 最新活动
	 */
	async function loadActivityData() {
		if (activityPagination.pageNo === 1) {
			activityList.value = [];
		}
		activityStatus.value = 'loading';
		const res = await qxActivityManageList({ baseLocationCode: proxy['vuex_location']['code'], ...unref(activityParams), ...activityPagination });
		activityTriggered.value = false;
		activityPagination.total = res?.total;
		activityList.value?.push(...res?.records);
		if (unref(activityList)?.length < activityPagination.total) {
			activityStatus.value = 'loadmore';
		} else {
			activityStatus.value = 'nomore';
		}
	}
	/**
	 * 顶部切换
	 */
	function handleTabs(item) {
		selectTab.value = item?.id;
		if (item?.id === 1) {
			pagination.pageNo = 1;
			loadData();
		}
	}
	// tabs 点击
	function handleTabClick(item) {
		console.log('item', item);
		activityParams.value.activityStatus = item?.id;
		activityPagination.pageNo = 1;
		loadActivityData();
	}

	/**
	 * 省市区打开
	 */
	function handleOpenLocation() {
		console.log(234);
		cityPickerVisible.value = true;
	}

	/**
	 * 省市区确认
	 */
	function confirm(val) {
		console.log(val);
		uni.$u.vuex('vuex_location', val);
		cancel();
	}

	/**
	 * 省市区取消
	 */
	function cancel() {
		cityPickerVisible.value = false;
	}

	/**
	 * 最新活动-滚动到底部操作
	 */
	function activityScrolltolower() {
		if (unref(activityList)?.length < activityPagination.total && (unref(activityList)?.length / activityPagination.pageSize == activityPagination.pageNo)) {
			activityPagination.pageNo++;
			loadActivityData();
		}
	}

	/**
	 * 自定义下拉刷新被触发-最新活动
	 */
	function activityOnRefresh() {
		activityTriggered.value = true;
		activityPagination.pageNo = 1;
		loadActivityData();
	}

	/**
	 * 研习基地列表数据
	 */
	async function loadData() {
		if (pagination.pageNo === 1 && !params.value?.search) {
			dataSouse.value = [];
		}
		status.value = 'loading';
		const res = await qxHomebaseManageList({ ...pagination, ...unref(params) });
		triggered.value = false;
		pagination.total = res?.total;
		if (params.value?.search) {
			dataSouse.value = res?.records;
		} else {
			dataSouse.value?.push(...res?.records);
		}
		if (dataSouse.value?.length === 1) {
			baseinfo.value = await qxHomebaseManageQueryById({ id: unref(dataSouse)[0]?.id })
		}
		if (unref(dataSouse)?.length < pagination.total) {
			status.value = 'loadmore';
		} else {
			status.value = 'nomore';
		}
	}

	/**
	 * 最新互动-滚动监听
	 */
	function handleActivityScroll({ detail }) {
		scrollTopView.value = detail?.scrollTop;
	}

	/**
	 * 滚动到底部操作
	 */
	function scrolltolower() {
		if (unref(dataSouse)?.length < pagination.total && (unref(dataSouse)?.length / pagination.pageSize == pagination.pageNo)) {
			pagination.pageNo++;
			loadData();
		}
	}

	/**
	 * 自定义下拉刷新被触发
	 */
	function onRefresh() {
		triggered.value = true;
		pagination.pageNo = 1;
		loadData();
	}

	/**
	 * 点赞/评论/转发 回调-最新活动
	 */
	function handleEmit(item, key) {
		const index = unref(activityList)?.findIndex(value => value?.id == item?.id);
		activityIndex.value = index;
		if (key === 'comment') {
			// uni.hideTabBar();
			//type 1 活动 2图集 3视频
			commentRef.value.handleShow({ activityId: item?.id, num: item?.comment ?? 0, belongId: item?.id, type: '1' });
		} else if (key === 'likes') {
			activityList.value[index]['izLike'] = item?.izLike;
			activityList.value[index]['likes'] = item?.likes;
		} else if (key === 'browse') {
			activityList.value[index]['browse'] = item?.browse;
		} else if (key === 'relay') {
			shareRef.value.handleShow({ path: 'pages/index/acitvityDetails', scene: `id=${item?.id}`, activityId: item?.id, title: item?.activityName });
		} else {
			activityList.value[index] = item;
		}
	}

	/**
	 * 评论回调
	 */
	function handleCommentClose(num) {
		uni.showTabBar();
		activityList.value[unref(activityIndex)]['comment'] = num;
	}

	/**
	 * 研习基地查询
	 */
	function handleSearchChange(value) {
		console.log(value, 'value');
		pagination.pageNo = 1
		params.value.search = value ?? '';
		uni.$u.throttle(loadData, 1000, false)
	}

	/**
	 * 轮播图点击
	 */
	function handleSwiperclick(index) {
		const item : any = swiperList.value[index];
		console.log(index, unref(item));
		console.log(item?.jumpUrl, 'sdf');
		if (item?.jumpType == '1') {//第三方
			console.log(item?.jumpUrl, 'sdf');
			uni.$u.route('/pages/index/webView', {
				url: item?.jumpUrl
			});
		} else {
			if (item?.isQx === 'hd') {
				uni.$u.route('/pages/index/acitvityDetails', {
					id: item?.jumpUrl
				});
			} else if (item?.isQx === 'jd') {
				uni.$u.route('/pages/index/baseDetails', {
					id: item?.jumpUrl
				});
			}
		}
		// uni.openurl
	}

	/**
	 * 基地回调
	 */
	function handleBaseEmit(item) {
		const index = unref(dataSouse)?.findIndex(value => value?.id == item?.id);
		dataSouse.value[index]['viewNum'] = item?.viewNum + 1;
	}
</script>

<style scoped lang="scss">
	.index {
		position: relative;

		// 顶部导航
		.index_navbar {
			height: 35vh;
			background-color: #FF943C;

			.index_navbar_top {
				width: 65%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 24rpx 0 20rpx 20rpx;

				.index_navbar_top_location {
					line-height: 56rpx;

					image {
						width: 32rpx;
						height: 32rpx;
						margin-right: 12rpx;
						vertical-align: middle;
					}

					text {
						font-size: 32rpx;
						color: #ffffff;
						font-weight: 600;
					}
				}

				.index_navbar_top_tabs {
					line-height: 56rpx;

					text {
						display: inline-block;
						color: #FFFFFF;
						font-size: 28rpx;
						vertical-align: middle;

						&:last-child {
							margin-left: 38rpx;
						}

						&.selected {
							font-size: 36rpx;
							font-weight: 600;
						}
					}
				}
			}
		}

		// 轮播图
		.index_swiper {
			padding: 0 24rpx;
			width: 94%;
		}

		.index_scroll_activity_view {
			position: absolute;
			top: 12.5vh;
			height: 87.2vh;
		}

		.index_body {
			position: relative;
			bottom: -30rpx;

			// 类型
			.index_function {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 24rpx;

				.index_function_item {
					display: flex;
					flex-direction: column;
					align-items: center;

					image {
						width: 84rpx;
						height: 84rpx;
					}

					text {
						display: block;
						font-size: 28rpx;
						// font-weight: bolder;
						text-align: center;
						margin-top: 16rpx;
					}
				}
			}

			// 研习活动
			.index_study {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 36rpx 24rpx 0 24rpx;

				.index_study_left {
					font-size: 40rpx;
					font-weight: 700;
				}

				.index_study_right {
					display: flex;
					align-items: center;
					color: #FF943C;
					font-size: 28rpx;
				}
			}

			::v-deep .u-tabs {
				.u-tabs__wrapper__nav__item {
					height: 76rpx !important;
					line-height: 76rpx !important;
				}
			}
		}

		.index_activity {
			padding-bottom: 20rpx;
		}

		.index_scroll_base {
			// position: absolute;
			// top: 160rpx;
			// width: 100%;

			.index_scroll_search {
				padding: 20rpx 24rpx;
				background-color: #ffffff;
				margin-bottom: 24rpx;
			}

			.index_scroll_base_view {
				height: 79vh;
			}
		}
	}

	::v-deep .pupop-btn {
		height: 30px !important;
	}

	// 客服按钮
	.index_service_btn {
		position: fixed;
		bottom: 48rpx;
		margin: 0;
		background-color: transparent;
		padding: 0;
		right: 30rpx;

		image {
			width: 92rpx;
			height: 92rpx;
			border-radius: 50%;
		}

		&::after {
			border: 0;
			height: auto;
		}
	}
</style>